package service

import (
	"strconv"
	"tiktok2023/model"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type FavoriteService struct {
}

func (f FavoriteService) HandleFavoriteAction(c *gin.Context) (resp *model.Response, err error) {
	var request struct {
		ActionType string `json:"action_type" form:"action_type"` // 1-点赞，2-取消点赞
		Token      string `json:"token" form:"token"`             // 用户鉴权token
		VideoID    string `json:"video_id" form:"video_id"`       // 视频id
	}
	if err := c.ShouldBind(&request); err != nil {
		return nil, err
	}

	userId := c.GetUint64("userId")
	videoId, err1 := strconv.Atoi(request.VideoID)
	if err1 != nil {
		return nil, err1
	}

	like := model.LikesTable{}
	err = model.Db.Where("user_id = ? AND video_id = ?", userId, videoId).First(&like).Error
	if err != nil {
		if err != gorm.ErrRecordNotFound {
			// 查询发生错误，返回错误信息
			return nil, err
		}

		// 点赞表中不存在记录，创建新记录
		like.UserId = userId
		like.VideoId = uint64(videoId)
		like.Cancel = 1
		err := model.Db.Create(&like).Error
		if err != nil {
			// 创建记录时发生错误，返回错误信息
			return nil, err
		}
	} else {
		// 点赞表中存在记录，更新点赞状态
		like.Cancel = 1
		err := model.Db.Save(&like).Error
		if err != nil {
			// 更新记录时发生错误，返回错误信息
			return nil, err
		}
	}

	return &model.Response{
		StatusCode: 0,
		StatusMsg:  "success",
	}, nil
}

type FavoriteListResponse struct {
	model.Response
	VideoList []model.Video `json:"video_list"`
}

func (f FavoriteService) HandleFavoriteList(c *gin.Context) (resp *FavoriteListResponse, err error) {

	var request struct {
		UserId string `json:"user_id" form:"user_id"` // 1-点赞，2-取消点赞
		Token  string `json:"token" form:"token"`     // 用户鉴权token
	}
	if err := c.ShouldBind(&request); err != nil {
		return nil, err
	}

	userId, err := strconv.ParseUint(request.UserId, 10, 64)

	// 查询用户的信息
	user := model.TableUser{}
	if err := model.Db.Where("id = ?", userId).First(&user).Error; err != nil {
		return nil, err
	}
	// 对用户的点赞视频进行查询
	videoIds := []uint64{}
	if err := model.Db.Table("likes").Select("video_id").Where("user_id = ? AND cancel = 1", userId).Find(&videoIds).Error; err != nil {
		return nil, err
	}
	// 再把视频信息查出来
	vedios := []model.VideosTable{}
	if err := model.Db.Where("id IN ?", videoIds).Find(&vedios).Error; err != nil {
		return nil, err
	}
	res := FavoriteListResponse{
		Response: model.Response{
			StatusCode: 0,
		},
	}
	// 再对结果进行绑定

	// 查询视频列表
	if err := model.Db.Where("id IN ?", videoIds).Find(&vedios).Error; err != nil {
		return nil, err
	}

	for _, i := range vedios {
		// 构造一个 model.Video 对象
		videoTemp := model.Video{
			Id:       i.Id,
			PlayUrl:  i.PlayUrl,
			CoverUrl: i.CoverUrl,
			Title:    i.Title,
			// 这里你可以手动填充 Author 字段，比如查询作者信息并赋值给 Author
		}

		// 手动填充 Author 字段
		userTemp := model.TableUser{}
		if err := model.Db.Where("id = ?", i.AuthorId).First(&userTemp).Error; err != nil {
			return nil, err
		}
		videoTemp.Author = userTemp

		res.VideoList = append(res.VideoList, videoTemp)
	}

	return &res, nil
}
